<!--
 * @Description:
 * @Author: FangYaoTang
 * @Date: 2023-08-16 09:19:08
 * @LastEditor: FangYaoTang
 * @LastEditTime: 2023-09-02 08:49:12
 * @Copyright: by 南京桓羽信息科技有限公司 禁止任何形式（包含二次开发）转售系统源码，违者必究。
-->

<template>
	<view class="page_content">
		<view class="head_content">
			<CustomNavbar title="Points recharge" color="#fff" bg="#241e42"></CustomNavbar>
		</view>
		<view class="main_content">
			<view class="box1">
				<view class="box_title">The point balance will never expire after recharging.</view>
				<view class="box_content">
					<view class="list_box">
						<view class="item" :class="{ active: item.id == integralActiveId, badge: item.flag }" :data-flag="item.flag"
							v-for="(item, index) in integralData" :key="item.id"
							@click="integralItem(item.id, item.amount, item.productId)">
							<view class="tag">Hot</view>
							<view class="line1">{{ item.score }} integral</view>
							<view class="line2">
								<text class="text1">$</text>
								<text class="text2">{{ item.amount }}</text>
							</view>
							<!-- <view class="line3">
                <text class="text">￥{{ item.original_price }}</text>
              </view> -->
							<!-- <view class="line4">
                <view class="">Virtual products</view>
                <view class="">Once recharged, it is non-refundable</view>
              </view> -->
						</view>
					</view>
					<view class="button_box">
						<u-button :loading="!buttonLoading" text="Recharge now" :customStyle="buttonStyle" @click="createOrder" />
					</view>
				</view>
			</view>
			<view class="box3">
				<view class="box_title">Notes on recharging now</view>
				<view class="box_content">
					<view class="text_info">
						<u-parse :content="textInfo"></u-parse>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex'
	import store from '@/common/store/index.js'
	export default {
		data() {
			return {
				buttonStyle: {
					width: '100%',
					height: '100rpx',
					border: 'none',
					fontSize: '38.73rpx',
					color: '#fff',
					background: '#243740',
					borderRadius: '27rpx',
					boxShadow: '0rpx 24rpx 35rpx 0rpx rgba(51,68,102,0.32)',
					margin: '0',
					fontWeight: 'bold',
				},
				buttonLoading: true,
				integralData: [],
				integralActiveId: 0,
				integralActivePrice: 0,
				textInfo: 'Notes on the introduction of BtcShort point package:<br /><br />1. Points package is a recharge method provided by BtcShort platform for users. By purchasing the point package, you can enjoy more on the platform services and privileges. <br /><br />2. The price and content of the points package will be announced on the platform, and users can choose a suitable package according to their needs. <br /><br />3. After purchasing the points package, the points will be directly recharged into your account and can be used to unlock paid content, participate in sweepstakes, purchase virtual gifts, etc. <br /><br />4. The points package has a certain validity period. Please use it within the validity period. After expiration, the remaining points will not be used, so please note. <br /><br />5. The points package is for personal use only and is prohibited from being transferred, sold or otherwise illegally traded. Once discovered, the platform will take corresponding measures. <br /><br />6. When using points, please abide by the relevant regulations of the platform and the user agreement, and do not publish illegal or illegal content involving politics, pornography, violence, etc. <br /><br />7. If you have any questions or concerns, you can contact our customer service team at any time, and we will answer and handle it for you as soon as possible. <br /><br />We adhere to the purpose of providing users with high-quality, safe and reliable services, and hope that you will enjoy a pleasant experience on the BtcShort platform. Thank you for your support and understanding!<br \/>',
				integralActivePId: '',
				isAndroid: true,
				iapChannel: null,
				// textInfo: '剧有钱短剧积分套餐介绍注意事项：<br \/><br \/>1. 积分套餐是剧有钱短剧平台为用户提供的一种充值方式，通过购买积分套餐可以在平台上享受更多的服务和特权。<br \/><br \/>2. 积分套餐的价格和内容会在平台上进行公示，用户可以根据自己的需求选择适合的套餐。<br \/><br \/>3. 购买积分套餐后，积分将直接充值到您的账户中，可以用于解锁付费内容、参加抽奖活动、购买虚拟礼物等。<br \/><br \/>4. 积分套餐具有一定的有效期，请在有效期内使用，过期后将无法使用剩余积分，敬请留意。<br \/><br \/>5. 积分套餐仅限个人使用，禁止转让、出售或以其他形式进行非法交易。一经发现，平台将采取相应的处理措施。<br \/><br \/>6. 在使用积分时，请遵守平台的相关规定和用户使用协议，不要发布涉及政治、色情、暴力等违法、违规内容。<br \/><br \/>7. 如有任何问题或疑问，您可以随时联系我们的客服团队，我们将尽快为您解答和处理。<br \/><br \/>我们秉承为用户提供高质量、安全可靠的服务的宗旨，希望您在剧有钱短剧平台上享受到愉快的使用体验。感谢您的支持与理解！<br \/>',
			}
		},
		computed: {
			...mapGetters('user', ['token']),
			...mapGetters('app', ['iosIsPay'])
		},
		watch: {},
		onLoad() {
			this.getIntegralList()
			var isAndroid = uni.getSystemInfoSync().platform == 'android'
			if (!isAndroid) {
				this.isAndroid = isAndroid
				this.loadAppleChannel()
			}
		},
		methods: {
			...mapActions('user', ['getUserInfo']),
			// 选择套餐
			integralItem(id, price, pId) {
				this.integralActiveId = id
				this.integralActivePrice = price
				this.integralActivePId = pId
			},
			loadAppleChannel() {
				let vm = this
				plus.payment.getChannels(function(channels) {
					console.log(channels, 'channels')
					for (var i in channels) {
						var channel = channels[i]
						// 获取 id 为 'appleiap' 的 channel
						if (channel.id === 'appleiap') {
							vm.iapChannel = channel
						}
					}
				}, function(e) {
					console.log('获取iap支付通道失败：' + e.message)
				})
			},
			// 获取积分套餐列表
			getIntegralList() {
				this.$request('integral.list').then(res => {
					if (res.data && res.data.length) {
						res.data.forEach(v => {
							if (v.amount == 8) {
								v.amount = 0.99
							} else if (v.amount == 78.00) {
								v.amount = 9.99
							} else if (v.amount == 88.00) {
								v.amount = 12.99
							}
						})
						this.integralData = res.data
						this.integralActiveId = res.data[0].id
						this.integralActivePrice = res.data[0].amount
						this.integralActivePId = res.data[0].productId
						console.log(res.data[0].productId, res.data[0])
					}
					// res.data.usable_desc && (this.textInfo = res.data.usable_desc.content)

				})
			},
			iosPay(id) {
				uni.showLoading({
					title: '支付中请勿离开',
					mask: true
				})
				uni.requestPayment({
					provider: 'appleiap',
					orderInfo: { productid: id, },
					success(res) {
						uni.hideLoading()
						uni.showToast({
							title: '充值成功',
							icon: 'none'
						})
						// 后续的操作，看自己的需求
						// 如刷新页面
						// 和后端确认是否支付成功
					},
					fail(err) {
						uni.hideLoading()
						uni.showToast({
							title: '支付已取消',
							icon: 'none'
						})
						console.log(err)
					},
					complete() {
						uni.hideLoading()
					}
				})
			},
			// 创建订单
			createOrder(item) {
        this.$request('order.create', { id: this.integralActiveId, type: 'jf' }).then((res) => {
          let {pay_url} = res.data
          try {
            plus.runtime.openURL(pay_url)
          } catch (err) {
            window.location.href = pay_url 
          }
        })
        return
				const token = store.state.user.token || ''
				if (!this.integralActiveId || !this.integralActivePrice)
					return this.$u.toast('Please select a points package')
				// this.recharge(this.integralActiveId, this.integralActivePrice)
				console.log(this.integralActivePId)
				if (token) {
					this.jumpView(
						`/pages/shouyitai/index?pay_amount=${this.integralActivePrice}&id=${this.integralActiveId}&productId=${this.integralActivePId}`
						)
				} else {
					uni.showModal({
						title: 'Login prompt',
						content: 'You have not logged in yet, please log in first',
						cancelText: 'Cancel',
						confirmText: 'Confirm',
						success: res => {
							if (res.confirm) {
								uni.redirectTo({ url: '/pages/login/login' })
							}
						}
					})
				}
				// if (this.isAndroid){
				//   this.jumpView(`/pages/shouyitai/index?pay_amount=${this.integralActivePrice}&id=${this.integralActiveId}`)
				// }else {
				//   let vm = this
				//   if (!vm.iapChannel){
				//     vm.loadAppleChannel()
				//   }
				//   let ids = ['com.juyouqian.top_8']
				//   // 转为字符串数组
				//   ids = ids.map(String)
				//   vm.iapChannel.requestOrder(ids, event => {
				//     vm.iosPay(event[0].productid)
				//   })
				// }
			},
			// 充值
			recharge(id, price) {
				// #ifdef H5
				if (!this.iosIsPay) return this.jumpView('/pages/user/info/contact')
				// #endif

				if (this.buttonLoading) {
					this.buttonLoading = false
					uni.showLoading({
						title: 'Loading...',
						mask: true
					})

					this.$request('integral.create', {
						usable_id: id,
						total_fee: price,
						platform: this.$utils.platforms()
					}).then(res => {
						if (res.code === 1) {
							this.callPay(res.data.order_sn, 'H5', res.data.platform)
						}
					})
				}
			},
			// 获取支付参数
			callPay(order_sn, payment, platform) {
				this.$request('common.ifxunipay').then(res => {
					console.log(res)
					if (res.data.xunipay_switch == 0) {
						this.$request('common.pay', {
							order_sn,
							payment,
							platform
						}).then(res => {
							console.log(res)
							if (res.code === 1) {
								if (platform == 'H5') {
									const div = document.createElement('divpay')
									div.innerHTML = res.data.pay_data
									document.body.appendChild(div)
								} else {
									this.pay(res.data.pay_data)
								}
							}
						})
					} else {
						// #ifdef H5
						uni.login({
							provider: 'weixin',
							success: success => {
								if (success.errMsg === 'login:ok') {
									this.$request('common.xunipay', {
										order_sn,
										payment,
										platform,
										code: success.code
									}).then(res => {
										console.log(res)
										if (res.code === 1) {
											if (platform == 'H5') {
												const div = document.createElement('divpay')
												div.innerHTML = res.data.pay_data
												document.body.appendChild(div)
											} else {
												this.xunipay(res.data.pay_data)
											}
										}
									})
								}
							}
						})
						// #endif
						// #ifndef H5

						this.$request('common.pay', {
							order_sn,
							payment,
							platform
						}).then(res => {
							console.log(res)
							if (res.code === 1) {
								if (platform == 'H5') {
									const div = document.createElement('divpay')
									div.innerHTML = res.data.pay_data
									document.body.appendChild(div)
								} else {
									this.pay(res.data.pay_data)
								}
							}
						})
						// #endif
					}
				})
			},
			// 发起 小程序/公众号 支付
			xunipay(pay) {
				var that = this
				// #ifdef H5
				const SDKVersion = wx.getSystemInfoSync().SDKVersion

				if (this.compareVersion(SDKVersion, '2.19.2') >= 0 || wx.canIUse('requestVirtualPayment')) {
					wx.requestVirtualPayment({
						signData: JSON.stringify({
							offerId: pay.signData.offerId,
							buyQuantity: pay.signData.buyQuantity,
							env: pay.signData.env,
							currencyType: pay.signData.currencyType,
							platform: pay.signData.platform,
							productId: pay.signData.productId,
							goodsPrice: pay.signData.goodsPrice,
							outTradeNo: pay.signData.outTradeNo,
							attach: pay.signData.attach
						}),
						paySig: pay.paySig,
						signature: pay.signature,
						mode: pay.mode,
						success(res) {
							//console.log('requestVirtualPayment success', res)
							uni.showToast({
								title: 'success',
								icon: 'none',
								duration: 2000
							})
							that.buttonLoading = true
							that.getUserInfo()
							uni.$emit('updateUserInfo', true)
							uni.hideLoading()
						},
						fail({
							errMsg,
							errCode
						}) {
							//console.error(errMsg, errCode)
							uni.showToast({
								title: 'fail',
								icon: 'none',
								duration: 2000
							})
							that.buttonLoading = true
							uni.hideLoading()
						}
					})
				} else {
					//console.log('当前用户的客户端版本不支持 wx.requestVirtualPayment')

					uni.showToast({
						title: 'The current user\'s client version does not support mini program virtual payment',
						icon: 'none',
						duration: 2000
					})
					this.buttonLoading = true
					uni.hideLoading()
				}
				// #endif

				// // #ifdef H5

				// WeixinJSBridge.invoke(
				// 	'getBrandWCPayRequest', {
				// 		"appId": pay.appId, // 公众号ID，由商户传入
				// 		"timeStamp": pay.timeStamp, // 时间戳，自1970年以来的秒数
				// 		"nonceStr": pay.nonceStr, // 随机串
				// 		"package": pay.package, // 订单详情扩展字符串
				// 		"signType": pay.signType, // 微信签名方式：
				// 		"paySign": pay.paySign // 微信签名
				// 	},
				// 	res => {
				// 		if (res.err_msg == "get_brand_wcpay_request:ok") {
				// 			uni.showToast({
				// 			    title: '支付成功',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			this.getUserInfo()
				// 			uni.$emit('updateUserInfo', true)
				// 			uni.hideLoading()
				// 		} else {
				// 			uni.showToast({
				// 			    title: '支付失败',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			uni.hideLoading()
				// 		}
				// 	});
				// // #endif

				// // #ifdef APP-PLUS
				// // APP
				// 	uni.getProvider({
				// 		service: "payment",
				// 		success: e => {
				// 			const type = e.provider.includes('wxpay')
				// 			type && uni.requestPayment({
				// 				"provider": "wxpay",
				// 				"orderInfo": pay,
				// 				success: success => {
				// 					uni.showToast({
				// 						title: '支付成功',
				// 						icon: 'none',
				// 						duration: 2000
				// 					});

				// 					this.buttonLoading = true
				// 					this.getUserInfo()
				// 					uni.$emit('updateUserInfo', true)
				// 					uni.hideLoading()
				// 				},
				// 				fail: fail => {
				// 					if(fail.errCode === -8) {
				// 						uni.showToast({
				// 							title: '未安装微信客户端',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					} else {
				// 						uni.showToast({
				// 							title: '支付失败',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					}
				// 				}
				// 			})
				// 		},
				// 		fail: e => {
				// 			this.payFail("获取iap支付通道失败")
				// 		}
				// 	});
				// // #endif
			},
			pay(pay) {
				// #ifdef H5
				uni.requestPayment({
					timeStamp: pay.timeStamp,
					nonceStr: pay.nonceStr,
					package: pay.package,
					signType: pay.signType,
					paySign: pay.paySign,
					success: success => {
						uni.showToast({
							title: 'success',
							icon: 'none',
							duration: 2000
						})
						this.buttonLoading = true
						this.getUserInfo()
						uni.$emit('updateUserInfo', true)
						uni.hideLoading()
					},
					fail: fail => {
						uni.showToast({
							title: 'fail',
							icon: 'none',
							duration: 2000
						})
						this.buttonLoading = true
						uni.hideLoading()
					}
				})
				// #endif

				// #ifdef H5
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						appId: pay.appId, // 公众号ID，由商户传入
						timeStamp: pay.timeStamp, // 时间戳，自1970年以来的秒数
						nonceStr: pay.nonceStr, // 随机串
						package: pay.package, // 订单详情扩展字符串
						signType: pay.signType, // 微信签名方式：
						paySign: pay.paySign // 微信签名
					},
					res => {
						if (res.err_msg == 'get_brand_wcpay_request:ok') {
							uni.showToast({
								title: '支付成功',
								icon: 'none',
								duration: 2000
							})
							this.buttonLoading = true
							this.getUserInfo()
							uni.$emit('updateUserInfo', true)
							uni.hideLoading()
						} else {
							uni.showToast({
								title: '支付失败',
								icon: 'none',
								duration: 2000
							})
							this.buttonLoading = true
							uni.hideLoading()
						}
					}
				)
				// #endif
				// #ifdef APP-PLUS
				// APP
				uni.getProvider({
					service: 'payment',
					success: e => {
						const type = e.provider.includes('wxpay')
						type &&
							uni.requestPayment({
								provider: 'wxpay',
								orderInfo: pay,
								success: success => {
									uni.showToast({
										title: '支付成功',
										icon: 'none',
										duration: 2000
									})

									this.buttonLoading = true
									this.getUserInfo()
									uni.$emit('updateUserInfo', true)
									uni.hideLoading()
								},
								fail: fail => {
									if (fail.errCode === -8) {
										uni.showToast({
											title: '未安装微信客户端',
											icon: 'none',
											duration: 2000
										})
										this.buttonLoading = true
										uni.hideLoading()
									} else {
										uni.showToast({
											title: '支付失败',
											icon: 'none',
											duration: 2000
										})
										this.buttonLoading = true
										uni.hideLoading()
									}
								}
							})
					},
					fail: e => {
						this.payFail('获取iap支付通道失败')
					}
				})
				// #endif
			},
			//判断微信js版本用
			compareVersion(_v1, _v2) {
				if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0

				const v1 = _v1.split('.')
				const v2 = _v2.split('.')
				const len = Math.max(v1.length, v2.length)

				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}

				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i], 10)
					const num2 = parseInt(v2[i], 10)

					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}

				return 0
			}
		}
	}
</script>

<style>
	page {
		background-color: white;
		min-height: 100vh;
	}
</style>
<style lang="scss" scoped>
	.page_content {
		background: #241e42;

		.main_content {
			padding: 24rpx 20rpx 60rpx 20rpx;
			overflow-y: auto;

			.box_title {
				font-size: 36rpx;
				color: #fff;
				font-weight: 700;
			}

			.box1 {
				margin-bottom: 36rpx;

				.box_content {
					.list_box {
						display: flex;
						flex-wrap: wrap;
						justify-content: space-between;
						margin: 40rpx 0 16rpx 0;

						.item {
							width: 224rpx;
							margin-bottom: 20rpx;
							border-radius: 10rpx;
							border: 2rpx solid transparent;
							box-shadow: 0 0 12rpx rgba(153, 153, 153, 0.16);
							text-align: center;
							padding: 60rpx 0 50rpx 0;
							background-color: #fff;
							font-size: 34.5rpx;
							position: relative;
							font-weight: 900;

							.tag {
								position: absolute;
								right: -16rpx;
								top: 10rpx;
								background: #F4453C;
								border-radius: 15rpx;
								font-size: 24rpx;
								padding: 5rpx 10rpx;
								font-weight: 500;
								color: #fff;
							}

							&.active {
								background-clip: padding-box, border-box;
								background-origin: padding-box, border-box;
								background: #243740;
								color: #fff;

								.line2 {
									color: #feb787;

									@supports (-webkit-background-clip: text) or (background-clip: text) {
										background: linear-gradient(to right, #feb787 20%, #f18a43 100% 100%);
										-webkit-background-clip: text;
										background-clip: text;
										color: transparent;
									}
								}

								.line3 {
									color: #feb787;
								}
							}

							&.badge {
								position: relative;

								&::before {
									// content: '限时优惠';
									content: attr(data-flag);
									position: absolute;
									top: 0;
									right: -2rpx;
									transform: translate(0, -50%);
									background: linear-gradient(90deg, #f28b45 0%, #feb787 100%);
									font-size: 24rpx;
									color: #fff;
									padding: 4rpx 10rpx;
									border-radius: 8rpx;
								}
							}

							.line1 {
								font-size: 32rpx;
							}

							.line2 {
								margin: 20rpx 0;

								.text1 {
									font-family: 59--Regular;
									font-size: 24rpx;
									color: #6C99D3;
									font-weight: 400;
								}

								.text2 {
									font-family: 59--Regular;
									font-weight: 400;
									font-size: 52rpx;
									color: #6C99D3;
								}
							}

							.line3 {
								font-size: 24rpx;
								text-decoration: line-through;
								margin-bottom: 8rpx;
							}

							.line4 {
								font-size: 24rpx;
								color: rgba(153, 153, 153, 1);
							}
						}
					}
				}
			}

			.box3 {
				.box_content {
					margin-top: 24rpx;

					.text_info {

						background: #243740;
						border-radius: 20rpx;
						font-size: 24rpx;
						color: #7f7f7f;
						padding: 24rpx 32rpx;
						border-radius: 20rpx;
						line-height: 36rpx;
					}
				}
			}
		}
	}
</style>